package com.itheima.dubbo.api.mongo.impl;


import cn.hutool.core.collection.CollUtil;
import com.itheima.dubbo.api.mongo.MovementApi;
import com.itheima.dubbo.utils.IdWorker;
import com.itheima.dubbo.utils.TimeLineUtils;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import javafx.animation.Timeline;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineUtils timeLineUtils;


    @Override
    public void save(Movement movement) {
        //1. 给movement补全pid
        movement.setPid(idWorker.getNextId("movement"));
        mongoTemplate.save(movement);
        //2. 查询当前用户的好友
       /* Query query = new Query(Criteria.where("userId").is(movement.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //3. 遍历该用户的所有好友,往时间线表插入数据
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (Friend friend : friendList) {
            MovementTimeLine timeLine = new MovementTimeLine();
            timeLine.setMovementId(movement.getId());
            timeLine.setUserId(friend.getUserId());
            timeLine.setFriendId(friend.getFriendId());
            timeLine.setCreated(System.currentTimeMillis());
            mongoTemplate.save(timeLine);
        }*/
       //该方法就是一个异步的方法，调用该方法的时候回单独开启一个线程 去执行该方法。
        timeLineUtils.saveTimeLine(movement);

    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
         Query query = new Query(Criteria.where("userId").is(userId));
         //1.查询总记录数
        long count = mongoTemplate.count(query, Movement.class);
         //2. 查询页面的数据
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        return new PageResult(page.longValue(),pagesize.longValue(),count,movementList);
    }

    @Override
    public PageResult findFriendMovements(Integer page, Integer pagesize, Long userId) {
        //1. 查询时间线表，得到我能够查看动态的id集合。
        Query query = new Query(Criteria.where("friendId").is(userId));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);

        //2 .根据动态id查询Movenment表得到相关数据
        Query movementQuery = new Query(Criteria.where("id").in(movementIds));
        long count = mongoTemplate.count(movementQuery, Movement.class);
        movementQuery.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movementList = mongoTemplate.find(movementQuery, Movement.class);
        return new PageResult(page.longValue(),pagesize.longValue(),count,movementList);
    }


    //随机查询动态的数据
    @Override
    public List<Movement> randomMovements(Integer pagesize) {
        //Aggregation.sample(10) 指定随机生成的数量，
        TypedAggregation typedAggregation = new TypedAggregation(Movement.class,Aggregation.sample(10));
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(typedAggregation, Movement.class);
        return aggregate.getMappedResults();
    }

    @Override
    public List<Movement> findByPids(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));
        return mongoTemplate.find(query,Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        Movement movement = mongoTemplate.findById(new ObjectId(movementId), Movement.class);
        return movement;
    }

    @Override
    public void updateMovement(String movementId, int state) {
        Query query = new Query(Criteria.where("id").is(new ObjectId(movementId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }


}